package com.coffee.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coffee.core.util.DateUtil;
import com.coffee.order.api.inquire.service.InquireOrderService;
import com.coffee.order.api.sku.service.PayOrderService;
import com.coffee.web.utils.WeixinSignHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;

import com.coffee.order.api.utils.*;

@Slf4j
@Controller
public class NotifyWeixinPayController {

    @Value("${parameter.weixin.mchId}")
    public String mchId;
    @Value("${parameter.weixin.appId}")
    public String appId;
    @Value("${parameter.weixin.signKey}")
    public String signKey;

    @DubboReference
    private InquireOrderService inquireOrderService;
    @DubboReference
    private PayOrderService payOrderService;


    @ResponseBody
    @RequestMapping("/wechat/applet/notifyUrl")
    public void payNotifyNewByWechatApplet(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("application/xml");
        log.info("微信小程序支付回调:/wechat/applet/notifyUrl");
        PrintWriter out = response.getWriter();
        try {
            Map<String, String> map = MessageUtil.parseXml(request);
            log.info("微信小程序支付回调接收到的参数====>>>" + JSON.toJSONString(map, true));
            SortedMap<String, String> parameters = new TreeMap<String, String>();
            for (Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                parameters.put(key, value);
            }
            String characterEncoding = "UTF-8";
            String mySign = WeixinSignHelper.createSign(characterEncoding, parameters, signKey);
            payOrderService.insertWeixinNotifyParameter(map);
            if (mySign.equals(map.get("sign"))) {
                // 处理业务
                String outTradeNo = map.get("out_trade_no");// 内部订单号
                Integer totalFee = Integer.valueOf(map.get("total_fee"));
                String timeEnd = map.get("time_end");
                String billNo = map.get("transaction_id");
                Date payTime = DateUtil.getDateForYyyyMMddHHmmss(timeEnd);
                String amount = new BigDecimal(totalFee).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN).toString();
                Integer payOrderId = Integer.parseInt(outTradeNo.split("-")[1]);
                inquireOrderService.notifyRecharge(payOrderId, billNo, payTime, map);
                PayStatus payStatus = new PayStatus();
                payStatus.setReturnCode("SUCCESS");
                payStatus.setReturnMsg("OK");
                String xml = MessageUtil.payStatusToXml(payStatus);
                out.print(xml);
                out.flush();
                out.close();
                return;
            } else {
                log.error("微信小程序支付回调签名错误:" + JSONObject.toJSONString(map));
            }
        } catch (Exception e) {
            log.error("-----------微信回调错误,解析xml出错:", e);
            e.printStackTrace();
            return;
        }

    }
}